package com.qf.service.impl;

import com.qf.mapper.AccountMapper;
import com.qf.pojo.Account;
import com.qf.pojo.ResultEnum;
import com.qf.service.AccountService;
import com.qf.web.exs.BusinessException;
import com.utils.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public Account findById(Integer id) {
        return accountMapper.findById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transfer(Integer outId, String inName, Double money) {
        //目标账号是否存在
        Account inAccount = accountMapper.findByName(inName);
        if (inAccount == null){
            throw new BusinessException(ResultEnum.OUT_ACCOUNT_NOT_EXISTS);
        }

        //转账金额是否充足
        Account outAccount = accountMapper.findById(outId);
        if (outAccount == null){
            throw new BusinessException(ResultEnum.IN_ACCOUNT_NOT_EXISTS);
        }
        if (outAccount.getMoney()<money){
            throw new BusinessException(ResultEnum.MONEY_NOT_ENOUGH);
        }

        //开始转账
        //转入
        accountMapper.updateMoneyByName(inName,money);

//        int i = 1/0;

        //转出
        accountMapper.updateMoneyByName(outAccount.getName(),-money);
    }

    @Override
    public List<Account> findAll() {
        return accountMapper.findAll();
    }

    @Override
    public int update(Account account) {
        return accountMapper.update(account);
    }

    @Override
    public List<Account> findByUid(int uid) {
        return accountMapper.findByUid(uid);
    }

    @Override
    public int add(Account account) {
        //补全业务数据
        Integer uid = ThreadLocalUtils.getUid();
        account.setUid(uid);

        return accountMapper.insert(account);
    }

    @Override
    public int deleteById(Integer id) {
        return accountMapper.deleteById(id);
    }
}
